import React, { Component } from "react";
import { View, StyleSheet, Alert, TouchableOpacity } from "react-native";

import Barcode from "react-native-smart-barcode";
import TimerEnhance from "react-native-smart-timer-enhance";
import { StackActions, NavigationActions } from "react-navigation";
import NavBarConfig from "../modules/NavBar";

class BarcodeComponent extends Component {
  static navigationOptions = ({ navigation }) =>
    NavBarConfig(
      {
        headerTitle: "扫描二维码",
        headerRight: null
      },
      navigation
    );
  // 构造
  constructor(props) {
    super(props);
    // 初始状态
    this.state = {
      viewAppear: false
    };
  }

  componentWillMount() {
    // const params = this.props.navigation.state.params;
    // alert(JSON.stringify(params));
  }
  render() {
    return (
      <View style={{ flex: 1, backgroundColor: "black" }}>
        <Barcode
          style={{ flex: 1 }}
          ref={component => (this._barCode = component)}
          onBarCodeRead={this._onBarCodeRead}
        >
          {this.props.children}
        </Barcode>
      </View>
    );
  }

  _onBarCodeRead = e => {
    try {
      let qrcodeData = JSON.parse(e.nativeEvent.data.code);
      const resetAction = StackActions.reset({
        index: 1,
        actions: [
          NavigationActions.navigate({
            routeName: "Home"
          }),
          NavigationActions.navigate({
            routeName: qrcodeData.path,
            params: qrcodeData.params
          })
        ]
      });
      this.props.navigation.dispatch(resetAction);
      this._stopScan();
    } catch (e) {
      alert("暫不支持其他類型碼，請掃描BGT的認購與劃轉的二維碼喔～");
      this.props.navigation.goBack();
    }
  };

  _startScan = e => {
    this._barCode.startScan();
  };

  _stopScan = e => {
    this._barCode.stopScan();
  };
}

export default TimerEnhance(BarcodeComponent);
